package code.rocky.offer1;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * offer03: 数组中重复的数字
 * addr: https://leetcode.cn/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
 */
public class offer03 {

    public static void main(String[] args) {
        int[] nums = new int[]{2, 3, 1, 0, 2, 5, 3};
        offer03 offer03 = new offer03();
        System.out.println(offer03.findRepeatNumber(nums));
        System.out.println(offer03.findRepeatNumber1(nums));
    }

    public int findRepeatNumber(int[] nums) {
        int length = nums.length;
        if (length == 0) return 0;
        Set<Object> set = new HashSet<>();
        for (int num : nums) {
            if (!set.add(num)) {
                return num;
            }
        }
        return 0;
    }

    /**
     *
     * @param nums
     * @return
     */
    public int findRepeatNumber1(int[] nums) {
        int length = nums.length;
        if (length == 0) return 0;
        int i = 0;
        while(i < length) {
            if(nums[i] == i) {
                i++;
                continue;
            }
            if(nums[nums[i]] == nums[i]) return nums[i];
            int tmp = nums[i];
            nums[i] = nums[tmp];
            nums[tmp] = tmp;
        }
        return -1;
    }
}
